import React, {
  ReactNode,
  Reducer,
  ReducerState,
  useEffect,
  useLayoutEffect,
  useMemo,
  useReducer,
  useState,
} from 'react';
import {
  Canvas,
  Circle,
  Group,
  matchFont,
  Shadow,
  Text,
  useFonts,
  useSVG,
  ImageSVG,
  Skia,
  Rect,
  Path,
  Image,
  useImage,
  StrokeCap,
  StrokeJoin,
  SweepGradient,
  vec,
  LinearGradient,
  RadialGradient,
  useClock,
  SkPoint,
  interpolate,
  SkPath,
  SkRect,
  listFontFamilies,
  SkSVG,
  Paragraph,
  TextAlign,
  FontWeight,
  RoundedRect,
  SkParagraph,
} from '@shopify/react-native-skia';
import {
  useSharedValue,
  withTiming,
  withRepeat,
  useDerivedValue,
  withSequence,
  Easing,
  cancelAnimation,
  Animation,
  TimingAnimation,
} from 'react-native-reanimated';
import { useAppTheme } from 'tsun-smart-ui';
import {
  BatteryIcon,
  EnergyDiagramBackground,
  EnergyDiagramDarkBackground,
  InverterDarkIcon,
  InverterIcon,
  PhotovoltaicDarkIcon,
  PhotovoltaicIcon,
  PowerGridIcon,
  PowerLoadIcon,
  useThemedSkiaSVG,
} from '../EnergyDiagram.types';
import { useTranslation } from 'react-i18next';
import { StationEnergyDiagramModel } from '@/services/api/stationApi';
import { useGetTheme } from '@/hooks/useTheme';
import {
  DIAGRAM_HEIGHT_FOR_ONE_NODE,
  DIAGRAM_HEIGHT_FOR_THREE_NODE,
  DIAGRAM_HORIZONTAL_PADDING,
  DIAGRAM_VERTICAL_PADDING,
  ENERGY_GRADIENT_RADIUS,
  GAP_BETWEEN_LINE_AND_NODE,
  HALF_NODE_BACKGROUND_SIZE,
  LINE_CORNER_RADIUS,
  LINE_STROKE_WIDTH,
  NODE_BACKGROUND_SIZE,
} from './Constants';
import EnergyNode from './EnergyNode';
import SingleNodeDiagram from './SingleNodeDiagram';
import ThreeNodeDiagram from './ThreeNodeDiagram';

type EnergyDiagramProps = {
  diagramData: StationEnergyDiagramModel;
  realtimeMode: boolean;
};

/// 电网
// const powerGridSVG = Skia.SVG.MakeFromString(PowerGridIcon);
// /// 负载
// const powerLoadSVG = Skia.SVG.MakeFromString(PowerLoadIcon);
// /// 储能
// const batterySVG = Skia.SVG.MakeFromString(BatteryIcon);

// /// 光伏到逆变器的线
// const lineBetweenPhotovoltaicAndInverter = Skia.Path.Make();

// /// 逆变器到负载的线
// const lineBetweenInverterAndLoad = Skia.Path.Make();

// /// 逆变器到储能的线
// const lineBetweenInverterAndBattery = Skia.Path.Make();

// /// 储能到电网的线
// const lineBetweenBatteryAndGrid = Skia.Path.Make();

const EnergyDiagram: React.FC<EnergyDiagramProps> = (props) => {
  const { t } = useTranslation();
  const havePhotovoltaicNode = Boolean(props.diagramData.otherNode?.pv);
  const haveBatteryNode = Boolean(props.diagramData.otherNode?.bat);
  const haveGridNode = Boolean(props.diagramData.otherNode?.grid);
  const haveLoadNode = Boolean(props.diagramData.otherNode?.load);
  const haveInverterNode =
    haveBatteryNode || haveLoadNode || havePhotovoltaicNode || haveGridNode;

  const photovoltaicSVG = useThemedSkiaSVG(
    PhotovoltaicIcon,
    PhotovoltaicDarkIcon
  );
  const inverterSVG = useThemedSkiaSVG(InverterIcon, InverterDarkIcon);

  // useLayoutEffect(() => {
  //   lineBetweenPhotovoltaicAndInverter.reset();
  //   lineBetweenInverterAndLoad.reset();
  //   lineBetweenInverterAndBattery.reset();
  //   lineBetweenBatteryAndGrid.reset();

  //   if (havePhotovoltaicNode && haveInverterNode) {
  //     /// 光伏到逆变器的线
  //     lineBetweenPhotovoltaicAndInverter.moveTo(
  //       props.width * 0.5,
  //       NODE_BACKGROUND_SIZE - GAP_BETWEEN_LINE_AND_NODE
  //     );
  //     lineBetweenPhotovoltaicAndInverter.lineTo(
  //       props.width * 0.5,
  //       NODE_BACKGROUND_SIZE + 48 + GAP_BETWEEN_LINE_AND_NODE
  //     );
  //     lineBetweenPhotovoltaicAndInverter.stroke({
  //       width: LINE_STROKE_WIDTH,
  //       cap: StrokeCap.Round,
  //       join: StrokeJoin.Round,
  //     });
  //   }

  //   if (haveInverterNode && haveLoadNode) {
  //     /// 逆变器到负载的线
  //     lineBetweenInverterAndLoad.moveTo(
  //       props.width * 0.5,
  //       props.height * 0.5 - HALF_NODE_BACKGROUND_SIZE
  //     );
  //     lineBetweenInverterAndLoad.lineTo(
  //       props.width * 0.5,
  //       props.height - HALF_NODE_BACKGROUND_SIZE - DIAGRAM_VERTICAL_PADDING
  //     );
  //     lineBetweenInverterAndLoad.stroke({
  //       width: LINE_STROKE_WIDTH,
  //       cap: StrokeCap.Round,
  //       join: StrokeJoin.Round,
  //     });
  //   }

  //   if (haveInverterNode && haveBatteryNode) {
  //     /// 逆变器到储能的线
  //     lineBetweenInverterAndBattery.moveTo(
  //       props.width * 0.5,
  //       props.height * 0.5 - HALF_NODE_BACKGROUND_SIZE * 0.5
  //     );
  //     lineBetweenInverterAndBattery.lineTo(
  //       HALF_NODE_BACKGROUND_SIZE +
  //         DIAGRAM_HORIZONTAL_PADDING +
  //         LINE_CORNER_RADIUS,
  //       props.height * 0.5 - HALF_NODE_BACKGROUND_SIZE * 0.5
  //     );
  //     lineBetweenInverterAndBattery.quadTo(
  //       HALF_NODE_BACKGROUND_SIZE + DIAGRAM_HORIZONTAL_PADDING,
  //       props.height * 0.5 - HALF_NODE_BACKGROUND_SIZE * 0.5,
  //       HALF_NODE_BACKGROUND_SIZE + DIAGRAM_HORIZONTAL_PADDING,
  //       props.height * 0.5 -
  //         HALF_NODE_BACKGROUND_SIZE * 0.5 +
  //         LINE_CORNER_RADIUS
  //     );
  //     lineBetweenInverterAndBattery.lineTo(
  //       HALF_NODE_BACKGROUND_SIZE + DIAGRAM_HORIZONTAL_PADDING,
  //       props.height - HALF_NODE_BACKGROUND_SIZE - DIAGRAM_VERTICAL_PADDING
  //     );
  //     lineBetweenInverterAndBattery.stroke({
  //       width: LINE_STROKE_WIDTH,
  //       cap: StrokeCap.Round,
  //       join: StrokeJoin.Round,
  //     });
  //   }

  //   if (haveInverterNode && haveGridNode) {
  //     /// 逆变器到电网的线
  //     lineBetweenBatteryAndGrid.moveTo(
  //       props.width * 0.5,
  //       props.height * 0.5 - HALF_NODE_BACKGROUND_SIZE * 0.5
  //     );
  //     lineBetweenBatteryAndGrid.lineTo(
  //       props.width -
  //         HALF_NODE_BACKGROUND_SIZE -
  //         DIAGRAM_HORIZONTAL_PADDING -
  //         LINE_CORNER_RADIUS,
  //       props.height * 0.5 - HALF_NODE_BACKGROUND_SIZE * 0.5
  //     );
  //     lineBetweenBatteryAndGrid.quadTo(
  //       props.width - HALF_NODE_BACKGROUND_SIZE - DIAGRAM_HORIZONTAL_PADDING,
  //       props.height * 0.5 - HALF_NODE_BACKGROUND_SIZE * 0.5,
  //       props.width - HALF_NODE_BACKGROUND_SIZE - DIAGRAM_HORIZONTAL_PADDING,
  //       props.height * 0.5 -
  //         HALF_NODE_BACKGROUND_SIZE * 0.5 +
  //         LINE_CORNER_RADIUS
  //     );
  //     lineBetweenBatteryAndGrid.lineTo(
  //       props.width - HALF_NODE_BACKGROUND_SIZE - DIAGRAM_HORIZONTAL_PADDING,
  //       props.height - HALF_NODE_BACKGROUND_SIZE - DIAGRAM_VERTICAL_PADDING
  //     );
  //     lineBetweenBatteryAndGrid.stroke({
  //       width: LINE_STROKE_WIDTH,
  //       cap: StrokeCap.Round,
  //       join: StrokeJoin.Round,
  //     });
  //   }
  // }, [
  //   havePhotovoltaicNode,
  //   haveInverterNode,
  //   haveBatteryNode,
  //   haveGridNode,
  //   haveLoadNode,
  //   props.diagramData,
  // ]);

  const pvDirectionNumber = props.diagramData.otherNode?.pv?.direction;
  const pvDirection: EnergyFlowDirection =
    pvDirectionNumber == 1 ? 'forward' : 'none';

  const batteryDirectionNumber = props.diagramData.otherNode?.bat?.direction;
  const batteryDirection: EnergyFlowDirection = getFlowDirectionAfterHouse(
    batteryDirectionNumber
  );

  const loadDirectionNumber = props.diagramData.otherNode?.load?.direction;
  const loadDirection: EnergyFlowDirection =
    getFlowDirectionAfterHouse(loadDirectionNumber);

  const gridDirectionNumber = props.diagramData.otherNode?.grid?.direction;
  const gridDirection: EnergyFlowDirection =
    getFlowDirectionAfterHouse(gridDirectionNumber);

  const nodeCount: number = 3;
  const diagramHeight =
    nodeCount === 1
      ? DIAGRAM_HEIGHT_FOR_ONE_NODE
      : DIAGRAM_HEIGHT_FOR_THREE_NODE;

  switch (nodeCount) {
    case 1:
      return <SingleNodeDiagram diagramData={props.diagramData} />;
    case 3:
      return <ThreeNodeDiagram />

    default:
      return null
  }
};

export default React.memo(EnergyDiagram);

export const HEIGHT_CONFIG = {
  DIAGRAM_HEIGHT: NODE_BACKGROUND_SIZE + 48 + NODE_BACKGROUND_SIZE + 8, // 多加一个内边距，不然阴影显示不全
  DIAGRAM_HEIGHT_WITH_OUTPUT:
    NODE_BACKGROUND_SIZE +
    48 +
    NODE_BACKGROUND_SIZE +
    48 +
    NODE_BACKGROUND_SIZE +
    8,
} as const;

type EnergyFlowDirection = 'forward' | 'backward' | 'none';

type EnergyStreamLineProps = {
  path: SkPath;
  energyStreamingDirection: EnergyFlowDirection;
  animationPointsIndexes: number[];
  energyColor?: string;
  animationDuration?: number;
  visible: boolean;
};

const EnergyStreamLine: React.FC<EnergyStreamLineProps> = React.memo(
  (props) => {
    const colorScheme = useGetTheme();
    const gradientPosition = useSharedValue<SkPoint>({ x: 0, y: 0 });
    const lineColor = colorScheme === 'dark' ? '#1D232B' : '#E9F0EF';
    const energyColor = props.energyColor ?? '#13C773';

    const animateToPoint = (
      targetX: number,
      targetY: number,
      duration: number = 2000
    ) => {
      'worklet';
      return withTiming(
        { x: targetX, y: targetY },
        {
          duration: duration,
          easing: Easing.linear,
        }
      );
    };

    useEffect(() => {
      cancelAnimation(gradientPosition);
      const animationDuration = props.animationDuration ?? 2000;
      let animationPoints: { x: number; y: number }[] = [];
      if (props.visible && props.animationPointsIndexes.length > 0) {
        let animationIndexes: number[] = [];
        if (props.energyStreamingDirection === 'forward') {
          animationIndexes = props.animationPointsIndexes;
        } else if (props.energyStreamingDirection === 'backward') {
          animationIndexes = props.animationPointsIndexes.reverse();
        }
        animationPoints = animationIndexes.map((index) =>
          animateToPoint(
            props.path.getPoint(index).x,
            props.path.getPoint(index).y,
            animationDuration
          )
        );
      }
      if (animationPoints.length > 0) {
        gradientPosition.value = withRepeat(
          withSequence(...animationPoints),
          -1,
          false
        );
      }
    }, [props.path, props.energyStreamingDirection, props.visible]);

    const showAnimation = props.energyStreamingDirection !== 'none';

    if (!props.visible) {
      return null;
    }
    return (
      <Path path={props.path} color={lineColor}>
        {showAnimation && (
          <RadialGradient
            c={gradientPosition}
            r={ENERGY_GRADIENT_RADIUS}
            colors={[energyColor, lineColor]}
            mode={'clamp'}
          />
        )}
      </Path>
    );
  }
);

const getFlowDirectionAfterHouse = (
  direction: number | null | undefined
): EnergyFlowDirection => {
  if (direction === 1) {
    return 'backward';
  } else if (direction === -1) {
    return 'forward';
  }
  return 'none';
};
